<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-input v-model="query.imgName" 
                    clearable 
                    placeholder="输入名称查找" 
                    @clear="getPage"
                    @keyup.enter.native="handleFilter" />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
        </el-col>
        <el-col :span="3" :offset="13">
          <el-button type="primary" 
                     icon="el-icon-user" 
                     @click="addImg"
                     round>添加镜像</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
        :data="pageList"
        stripe
        style="width: 100%">
        <el-table-column
          prop="imgId"
          label="镜像ID">
        </el-table-column>
        <el-table-column
          prop="owner"
          label="所有者"
          width="180">
        </el-table-column>
        <el-table-column
          prop="imgName"
          label="名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="format"
          label="格式"
          width="180">
        </el-table-column>
        <el-table-column
          prop="size"
          label="大小"
          width="180"
          :formatter="formatter">
        </el-table-column>
        <el-table-column 
          label="操作" 
          width="100">
          <template slot-scope="scope">
            <el-button 
              type="danger" 
              size="mini" 
              :disabled="ifNotGranted(scope.row)"
              @click="deleteImage(scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

    <el-dialog title="上传镜像" :visible.sync="dialogFormVisible">
          <el-form 
            ref="imgForm" 
            :rules="rules" 
            :model="temp" 
            size="small"
            label-position="right" 
            label-width="80px" 
            class="data-form">
        
            <el-form-item label="工号" prop="tid">
              <el-input v-model="temp.tid" readonly/>
            </el-form-item>
            <el-form-item label="名称" prop="imgName">
              <el-input v-model="temp.imgName" placeholder="输入镜像名称"/>
            </el-form-item>
            <el-form-item label="格式" prop="format">
              <el-select v-model="temp.format" placeholder="选择镜像格式">
                <el-option v-for="item in formats" :key="item.format" :label="item.name" :value="item.format" />
              </el-select>
            </el-form-item>
            <el-form-item label="镜像源" prop="file">
              <el-upload
                ref="upload"
                :action="uploadImage"
                :auto-upload="false"
                :before-upload="beforeUpload"
                :on-success="onSuccess"
                :on-error="onError"
                :data="temp"
                :limit="1">
                <el-button slot="trigger" size="small" type="primary">浏览</el-button>
              </el-upload>
              
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="temp.profile" 
                        :autosize="{ minRows: 2, maxRows: 4}" 
                        type="textarea" 
                        placeholder="在此输入具体描述" />
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="resetForm('imgForm')">重置</el-button>
            <el-button type="primary" @click="submitForm('imgForm')">确定</el-button>
          </div>
        </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getImages,uploadImage,deleteImage } from '@/api/stack'

export default {
  name: 'userList',
  components: {},
  data() {
    return {
      tableData: [],
      pageList:[],
      formats: [{format:'RAW', name:'raw-原始'},
                {format:'VHD', name:'VHD-虚拟硬盘'},
                {format:'VMDK', name:'VMDK-虚拟机磁盘'},
                {format:'VDI', name:'VDI-虚拟磁盘镜像'},
                {format:'ISO', name:'ISO-光盘镜像'},
                {format:'QCOW2', name:'QCOW2-QEMU模拟器'},],
      query:{
        tid: null,
        imgId: '',
        imgName: '',
        page: 1,
        limit: 10,
      },
      dialogFormVisible:false,
      rules: {
        imgName: [{ required: true, message: '请填写镜像名称', trigger: 'blur'}],
        format: [{ required: true, message: '请选择镜像格式', trigger: 'change'}],
        // file: [{ required: true, message: '请选择镜像源', trigger: 'change'}],
      },
      temp: {
        tid: null,
        imgName:null,
        format:null,
        profile: null,
      },
      uploadImage,
    }
  },
  computed: {
    ...mapGetters([
      'uid',
      'name',
    ]),
  },
  created() {
    this.query.tid = this.uid
    this.resetTemp()
    this.getImageList()
  },
  methods: {
    // 获取镜像列表
    getImageList() {
      getImages(this.query).then(response => {
        this.tableData = response.load.imageList
        this.getPage()
      }).catch(()=>{
        console.log("获取镜像列表失败")
      })
    },
    getPage(){
      this.pageList = this.tableData.filter((item, index) => 
        index < this.query.limit * this.query.page 
        && index >= this.query.limit * (this.query.page - 1))
    },
    handleFilter() {
      if(this.query.imgName){
        this.pageList = this.tableData.filter(v=>v.imgName.indexOf(this.query.imgName) >= 0)
      }else{
        this.getPage()
      }
    },
    // 添加镜像
    resetTemp() {
      this.temp = {
        tid: this.uid,
        imgName:null,
        format:null,
        profile: null,
      }
    },
    addImg(){
      this.dialogFormVisible = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit();
        } else {
          this.$message.error('请完善表单!')
        }
      });
    },
    resetForm(formName) {
      this.$refs.upload.clearFiles()
      this.$refs[formName].resetFields();
    },
    beforeUpload(file) {
      if (file.size / 1024**3 > 10) {
        this.$message.error('上传文件大小不能超过10GB哦!')
        console.log(file.size)
        return false
      }
    },
    onSuccess(res ){
      this.resetForm('imgForm')//成功后重置表单,清除验证信息
      this.resetTemp()//成功后重置表单
      this.dialogFormVisible = false
      this.$notify({
        title: '成功',
        message: `成功上传镜像。`,
        type: 'success',
        duration: 2000
      })
      this.getImageList()
    },
    onError(err ){
      console.log(err) // for debug
      this.$message.error(err.messsage || 'upload image Error')
    },
    
    // 删除镜像
    deleteImage(row){
      this.query.imgId = row.imgId
      deleteImage(this.query).then(response => {
        this.$notify({
          title: '成功',
          message: `成功删除镜像。`,
          type: 'success',
          duration: 2000
        })
        this.getImageList()
      }).catch(()=>{
        console.log("删除镜像失败")
      })
    },
    ifNotGranted(row){
      return row.owner != this.name
    },
    //数据格式化
    formatter(row) {
      if(null==row.size||row.size==''){
        return "0 Bytes";
      }
      let unitArr = new Array(" Bytes"," KB"," MB"," GB","TB","PB","EB","ZB","YB");
      // let index=0;
      let index=Math.floor( Math.log(row.size)/Math.log(1024) );//向下取整
      let imgSize = (row.size/Math.pow(1024,index)).toFixed(2);//保留的小数位数
      
      return imgSize+unitArr[index];
    },
    
  },
  filters: {
  },
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 20px;
  .filter-container {
    margin-bottom: 20px;
  }
  .data-form{
    width: 70%;
    margin-left:50px;
  }
}

// .tags-view-container {
//   height: 40px;
//   width: 100%;
//   background: #fff;
//   overflow: hidden;
  
// }
// .content-container{
//   // height: calc(100vh - 40px - 50px);
// }
</style>
